import { v4 as uuidv4 } from 'uuid'

const UUID_KEY = 'visitor_uuid'

export const getOrGenerateUUID = (): string => {
  // 从cookie中获取uuid
  let uuid = document.cookie
    .split('; ')
    .find(row => row.startsWith(UUID_KEY))
    ?.split('=')[1]

  // 如果没有找到，生成新的uuid
  if (!uuid) {
    uuid = uuidv4()
    // 不设置expires，使其成为会话cookie
    document.cookie = `${UUID_KEY}=${uuid}; path=/`
  }

  return uuid
}
